// pages/discounts/add/index.js
import api from "../../../api/index";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      form: 'card'
    },
    isAdd: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},
  getValue(e) {
    let data = {};
    let name = e.currentTarget.dataset.name;
    data[`formData.${name}`] = e.detail.value;
    this.setData(data);
  },

  onRadioChange(e) {
    let name = e.currentTarget.dataset.name;
    if (name === "form") {
      this.setData({
        formData: {},
      });
    }
    let key = `formData.${name}`;
    let data = {
      [key]: e.detail,
    };
    this.setData(data);
  },
  onAdd() {
    let { formData, isAdd } = this.data;
    if (isAdd) return;
    this.setData({ isAdd: true });
    if (
      !formData.threshold ||
      !formData.face ||
      !formData.quantity ||
      !formData.rest ||
      !formData.days ||
      (formData.form === 'course' ? !formData.lessons : '')
    ) {
      wx.showToast({
        title: "必填参数不能为空",
        icon: "none",
      });
      this.setData({ isAdd: false });
      return;
    }
    let param = {
      ...formData
    };
    api
      .apiStoreCouponAdd(param)
      .then((res) => {
        if (res.code === 1) {
          wx.showToast({
            title: "添加成功",
            icon: "none",
          });
          setTimeout((_) => {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.init) {
              prevPage.init(true);
            }
            wx.navigateBack();
          }, 2500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      })
      .finally((_) => {
        this.setData({ isAdd: false });
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
